package com.xinghou.platform.server.api.bussiness.impl;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import com.xinghou.platform.lucene.main.StoreLuceneService;
import com.xinghou.platform.server.api.bussiness.DataConfigService;
import com.xinghou.platform.util.*;
import org.springframework.dao.DataAccessException;
import org.springframework.data.geo.Point;
import org.springframework.stereotype.Service;

import com.xinghou.platform.dao.main.CityDAO;
import com.xinghou.platform.dao.main.DataConfigDAO;
import com.xinghou.platform.dao.main.SharedCardDAO;
import com.xinghou.platform.dao.main.StoreDAO;
import com.xinghou.platform.dao.main.StoreImageDAO;
import com.xinghou.platform.dao.main.StoreLocationMONGO;
import com.xinghou.platform.dao.main.UserDAO;
import com.xinghou.platform.dao.main.UserGeoDAO;
import com.xinghou.platform.entity.req.ShopInfoReq;
import com.xinghou.platform.entity.resp.ShopInfoPhotoResp;
import com.xinghou.platform.entity.resp.ShopInfoResp;
import com.xinghou.platform.model.main.City;
import com.xinghou.platform.model.main.Store;
import com.xinghou.platform.model.main.StoreImage;
import com.xinghou.platform.model.main.StoreLocationGeo;
import com.xinghou.platform.model.main.User;
import com.xinghou.platform.model.main.UserGeo;
import com.xinghou.platform.server.api.bussiness.ShopInfoBusinessService;

@Service("shopInfoService")
public class ShopInfoBusinessServiceImpl implements ShopInfoBusinessService {
    @Resource
    private StoreDAO storeDAO;

    @Resource
    private DataConfigDAO dataConfigDAO;

    @Resource
    private StoreImageDAO storeImageDAO;

    @Resource
    private UserDAO userDAO;

    @Resource
    private UserGeoDAO userGeoDAO;

    @Resource
    private SharedCardDAO sharedCardDAO;

    @Resource
    private CityDAO cityDAO;

    @Resource
    private DataConfigService dataConfigService;

    @Resource
    public StoreLuceneService storeLuceneService;


    private String url = ConfigUtil.getProperty("shopimage_download");
    private String oldurl = ConfigUtil.getProperty("file_download") + "/store_img/";

    @Override
    public List<ShopInfoResp> getShopInfoList(String key, String frompage)
            throws DataAccessException {
        List<ShopInfoResp> ShopInfoResps = new ArrayList<ShopInfoResp>();
        ShopInfoResp shopInfoResp = null;
        //模糊查询出所有商铺名
        List<String> names = storeDAO.getStoreInfoLists(key, frompage);
        for (String name : names) {
            //模糊查询第一轮 统计结果数
            shopInfoResp = new ShopInfoResp();
            shopInfoResp.setShopname(name);
            shopInfoResp.setShopnum("-1");
            ShopInfoResps.add(shopInfoResp);
        }
        return ShopInfoResps;
    }

    @Override
    public List<ShopInfoResp> getStoreSearchList(ShopInfoReq shopInfoReq) throws DataAccessException {
        Double lon = Double.parseDouble(shopInfoReq.getLongitude());
        Double lat=Double.parseDouble(shopInfoReq.getLatitude());
        String key= null;
        try {
            key = URLDecoder.decode(shopInfoReq.getFindkey(), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Integer pagesize=Integer.parseInt(shopInfoReq.getPagesize());
        Integer pageno=Integer.parseInt(shopInfoReq.getPageno());
        Integer fromno=(pageno-1)*pagesize;
        Double distance=Double.parseDouble(shopInfoReq.getDistance());
       List<Store> stores= storeLuceneService.getSearchStoreInfos(false,key, fromno, pagesize, null, distance, lon, lat);
        if(stores==null||stores.isEmpty())
            return null;
        List<ShopInfoResp> shopInfoResps=new ArrayList<ShopInfoResp>();
        for(int i=0;i<stores.size();i++)
        {
            ShopInfoResp shopInfoResp=new ShopInfoResp();
            Double storelat=stores.get(i).getLatitude();
            Double storelon=stores.get(i).getLongitude();
            shopInfoResp.setShopname(stores.get(i).getName());
            shopInfoResp.setShopaddress(stores.get(i).getAddress());
            String dis=GeohashUtil.distanceOfTwoPointsTOString(lon,lat, storelon,storelat,GeohashUtil.GaussSphere.Beijing54);
            shopInfoResp.setDistance(dis);
            shopInfoResp.setShopid(stores.get(i).getId().toString());
            shopInfoResps.add(shopInfoResp);
        }
        return shopInfoResps;
    }

    //精确查询
    @Override
    public List<ShopInfoResp> getShopInfoDetailList(String key, String frompage, String userid)
            throws DataAccessException {
        ShopInfoResp shopInfoResp = null;
        List<ShopInfoResp> shopInfoResps = new ArrayList<ShopInfoResp>();
        List<Store> stores = storeDAO.getStoreListbyname(key, frompage);
        boolean flag = false;
        UserGeo userGeo = userGeoDAO.getUserGeoById(Integer.parseInt(userid));
        Double[] pos = new Double[2];
        for (Store store : stores) {
            flag = false;
            shopInfoResp = new ShopInfoResp();
            shopInfoResp.setAlias(key);//别名
            shopInfoResp.setShopid(store.getId() + "");
            shopInfoResp.setShopname(store.getName());//门店
            shopInfoResp.setStatus(store.getStatus().toString());
            shopInfoResp.setShopaddress(store.getAddress());//地址
            shopInfoResp.setShoppurl(store.getPhotos());
            shopInfoResp.setMoney(store.getConsume().toString());

            if (StringUtils.isNotBlank(store.getLongitude().toString()) && StringUtils.isNotBlank(store.getLatitude().toString())) {
                shopInfoResp.setLongitude(store.getLongitude().toString());
                shopInfoResp.setLatitude(store.getLatitude().toString());
            }
            if (userGeo != null)
                if (StringUtils.isNotBlank(userGeo.getLongitude().toString()) && StringUtils.isNotBlank(userGeo.getLatitude().toString())) {
                    pos[0] = userGeo.getLongitude();
                    pos[1] = userGeo.getLatitude();
                    flag = true;
                }

            shopInfoResp.setDistance("-1");
            if (flag) {
                if (store.getLongitude() != null && store.getLatitude() != null) {
                    shopInfoResp.setDistance(GeohashUtil.distanceOfTwoPointsTOString(store.getLongitude(), store.getLatitude(), pos[0], pos[1], GeohashUtil.GaussSphere.Beijing54));
                }
            }

            String type = dataConfigService.getStoreTag(store.getCategory_code());
            shopInfoResp.setShoptype(type);
            shopInfoResps.add(shopInfoResp);
        }
        return shopInfoResps;
    }

    @Override
    public List<ShopInfoResp> getShopInfoDetailList(String userid, String fromrowstr, int limit, int distance, String longitude, String latitude) throws DataAccessException {
        int fromrow = 0;
        if (Integer.valueOf(fromrowstr) == null || Integer.valueOf(fromrowstr) < 0) {
            fromrow = 0;
        } else {
            fromrow = Integer.valueOf(fromrowstr);
        }
        User user = userDAO.getUserById(Integer.valueOf(userid));
        UserGeo userGeo = userGeoDAO.getUserGeoById(Integer.valueOf(userid));
        Store store;
        List<Store> storeLocationGeos = new ArrayList<Store>();
        List<ShopInfoResp> shopInfoResps = new ArrayList<ShopInfoResp>();
        ShopInfoResp shopInfoResp = new ShopInfoResp();
        Double[] pos = new Double[2];

        if (StringUtils.isNotBlank(userGeo.getLongitude().toString()) && StringUtils.isNotBlank(userGeo.getLatitude().toString())) {
            pos[0] = userGeo.getLongitude();
            pos[1] = userGeo.getLatitude();

            if (null != longitude && null != latitude && Double.valueOf(longitude) > 0 && Double.valueOf(latitude) > 0) {
                pos[0] = Double.valueOf(longitude);
                pos[1] = Double.valueOf(latitude);
            }
            Point point = new Point(pos[0], pos[1]);
            try {
                // storeLocationGeos=storeLuceneService.getSearchStoreInfos(null,fromrow,limit,null,pos[1],pos[0]);
            } catch (Exception e) {
                e.printStackTrace();
            }

            for (int i = 0; i < storeLocationGeos.size(); i++) {
                store = storeDAO.getStoreBystoreId(storeLocationGeos.get(i).getId());
                shopInfoResp = new ShopInfoResp();
                setshopInfo(shopInfoResp, store, pos, true);
                shopInfoResps.add(shopInfoResp);
            }
        } else {
            City city = cityDAO.getNameByCode(user.getCitycode());
            if (StringUtils.isNotBlank(city.getLongitude().toString()) && StringUtils.isNotBlank(city.getLatitude().toString())) {
                pos[0] = city.getLongitude();
                pos[1] = city.getLatitude();

                Point point = new Point(pos[0], pos[1]);
                try {
                    //storeLocationGeos=storeLuceneService.getSearchStoreInfos(null,fromrow,limit,null,pos[1],pos[0]);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                for (int i = 0; i < storeLocationGeos.size(); i++) {
                    store = storeDAO.getStoreBystoreId(storeLocationGeos.get(i).getId());
                    shopInfoResp = new ShopInfoResp();
                    setshopInfo(shopInfoResp, store, pos, true);
                    shopInfoResps.add(shopInfoResp);
                }
            } else {
                List<Integer> storeids = sharedCardDAO.getStoreidListsortbysellcount(fromrow);
                for (Integer integer : storeids) {
                    store = storeDAO.getStoreBystoreId(integer);
                    shopInfoResp = new ShopInfoResp();
                    setshopInfo(shopInfoResp, store, pos, false);
                    shopInfoResps.add(shopInfoResp);
                }
            }

        }

        return shopInfoResps;
    }

    @Override
    public List<ShopInfoResp> getBranchShopInfoList(String userid, String shopid, String fromno) throws DataAccessException {
        return null;
    }

    public void setshopInfo(ShopInfoResp shopInfoResp, Store store, Double[] pos, boolean flag) {
        shopInfoResp.setAlias("");//别名
        shopInfoResp.setShopname(store.getName());//门店
        shopInfoResp.setShopaddress(store.getAddress());//地址
        shopInfoResp.setShopid(String.valueOf(store.getId()));
        shopInfoResp.setStatus(store.getStatus().toString());

        shopInfoResp.setShoppurl("");
        StoreImage storeImage = storeImageDAO.getStoreImageList(store.getId(), 999);
        if (storeImage != null) {
            shopInfoResp.setShoppurl(PhotoPathUtil.getStyle_670w440l(url + storeImage.getUri()));//缩略图
            //shopInfoResp.setShoppurl(url+storeImage.getUri().replace("D:/task", ""));//缩略图
        } else {
            storeImage = storeImageDAO.getFirstStoreImage(store.getId());
            if (storeImage != null) {
                shopInfoResp.setShoppurl(PhotoPathUtil.getStyle_670w440l(url + storeImage.getUri()));//缩略图
                //shopInfoResp.setShoppurl(url+storeImage.getUri().replace("D:/task", ""));//缩略图
                if (storeImage.getUri().startsWith("20")) {
                    shopInfoResp.setShoppurl(oldurl + storeImage.getUri());
                }
            }
        }
        shopInfoResp.setShoptype(dataConfigService.getStoreTag(store.getCategory_code()));
        shopInfoResp.setMoney(String.valueOf(store.getConsume()));

        if (StringUtils.isNotBlank(store.getLongitude().toString()) && StringUtils.isNotBlank(store.getLatitude().toString())) {
            shopInfoResp.setLongitude(store.getLongitude().toString());
            shopInfoResp.setLatitude(store.getLatitude().toString());

            shopInfoResp.setDistance("-1");
            if (flag) {
                if (StringUtils.isNotBlank(store.getLongitude().toString()) && StringUtils.isNotBlank(store.getLatitude().toString())) {
                    shopInfoResp.setDistance(GeohashUtil.distanceOfTwoPointsTOString(store.getLongitude(), store.getLatitude(), pos[0], pos[1], GeohashUtil.GaussSphere.Beijing54));
                }
            }

        }
    }



    public ShopInfoResp getShopInfoDetail(String userid, String shopid) throws DataAccessException {
        ShopInfoResp shopInfoResp = new ShopInfoResp();
        Store store = storeDAO.getStoreBystoreId(Integer.valueOf(shopid));
        UserGeo userGeo = userGeoDAO.getUserGeoById(Integer.parseInt(userid));
        if (store != null) {
            shopInfoResp.setAlias(store.getAlias_name());//别名
            shopInfoResp.setShopname(store.getName());//门店
            shopInfoResp.setShopaddress(store.getAddress());//地址
            shopInfoResp.setShopid(String.valueOf(store.getId()));
            shopInfoResp.setStatus(store.getStatus().toString());
            shopInfoResp.setShoppurl(store.getPhotos());
            shopInfoResp.setShoptype(dataConfigService.getStoreTag(store.getCategory_code()));
            if (StringUtils.isNotBlank(store.getLongitude().toString()) && StringUtils.isNotBlank(store.getLatitude().toString())) {
                shopInfoResp.setLongitude(store.getLongitude().toString());
                shopInfoResp.setLatitude(store.getLatitude().toString());
                if(userGeo!=null)
                shopInfoResp.setDistance(GeohashUtil.distanceOfTwoPointsTOString(store.getLongitude(), store.getLatitude(), userGeo.getLongitude(), userGeo.getLatitude(), GeohashUtil.GaussSphere.Beijing54));
                shopInfoResp.setMoney(String.valueOf(store.getConsume()));
                shopInfoResp.setHours(store.getOpentime());
                if (StringUtils.isNotBlank(store.getTelephone()))
                    shopInfoResp.setTelphone(store.getTelephone());
                else {
                    shopInfoResp.setTelphone("");
                }
                shopInfoResp.setShopphotos(store.getPhotos());

            }
        }

        return shopInfoResp;
    }

    public String distanceShopAndUser(String userid, String shopid) {
        Store store = storeDAO.getStoreBystoreId(Integer.valueOf(shopid));
        UserGeo userGeo = userGeoDAO.getUserGeoById(Integer.valueOf(userid));

        Double[] pos = new Double[2];
        if (userGeo == null || userGeo.getLongitude() == null || userGeo.getLatitude() == null) {
            return "-1";
        }
        pos[0] = userGeo.getLongitude();
        pos[1] = userGeo.getLatitude();
        if (pos[0] == null || pos[1] == null || pos[0] < 0 || pos[1] < 0) {
            return "-1";
        } else if (pos[0] == 0 || pos[1] == 0) {
            User user = userDAO.getUserById(Integer.valueOf(userid));
            City city = cityDAO.getNameByCode(user.getCitycode());
            if (city.getLongitude() == null || city.getLatitude() == null) {
                return "-1";
            } else {
                pos[0] = city.getLongitude();
                pos[1] = city.getLatitude();
            }
        }

        if (null != store.getLongitude() && null != store.getLatitude())
            return GeohashUtil.distanceOfTwoPointsTOString(store.getLongitude(), store.getLatitude(), pos[0], pos[1], GeohashUtil.GaussSphere.Beijing54);
        else {
            return "-1";
        }
    }

    @Override
    public int addShopInfo(ShopInfoReq shopInfoReq) throws DataAccessException {
        return 0;
    }

}
